package cn.wolfcode.thread;

import java.util.Random;

public class TestCAS {
    public static void main(String[] args) {
        Cas cas = new Cas();
        for (int i = 0; i <5 ; i++) {
            new Thread(new Runnable() {
                public void run() {
                    //获取内存值
                    int expectValue = cas.get();
                    int newValue = new Random().nextInt(100);
//                    System.out.println(expectValue+","+newValue);
                    /*boolean flag = cas.compareAndSet(expectValue, newValue);
                    System.out.println(flag+","+expectValue+","+newValue+","+cas.get());*/
                    int oldvalue = cas.compareAndSwap(expectValue, newValue);
                    System.out.println(expectValue+","+oldvalue+","+newValue+","+cas.get());
                }
            }).start();

        }
    }
}

class Cas {
    private int value;

    //获取值
    public int get(){
        return value;
    }
    public synchronized int compareAndSwap (int expectValue,int newValue){
        int oldValue = this.value;
        if (expectValue==oldValue){
            this.value=newValue;
        }
        return oldValue;
    }
    public boolean compareAndSet(int expectValue,int newValue){
        return expectValue==compareAndSwap(expectValue,newValue);
    }
}
